﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyFloridaHouse.libPrint.BingMapAjaxHelpers;

namespace  MyFloridaHouse.libPrint.KML
{
    public static class KMLPointReduction
    {
        public static IList<Point> GeneralizePolyPoints(IList<Point> iPolyPts, int reduceZoomLevel)
        {
            //int zoomLevel = 12; //Going lower, such as 8 speeds things up but makes thing the generalization 
            //too great.  However, going beyond 9 slows thing down to a point the browser won't take
            Point point = new Point();
            List<Point> processedPoints = new List<Point>();
            for (int p = 0; p < iPolyPts.Count; p++)
            {
                point = iPolyPts[p];
                double stx = double.Parse(point.Longitude.ToString());
                double xp = .01098632 / Math.Pow(2, reduceZoomLevel - 7);
                double x = Convert.ToInt32(Math.Abs(stx) / xp) * xp;
                double sty = double.Parse(point.Latitude.ToString());
                double yp = .009698274 / Math.Pow(2, reduceZoomLevel - 7);
                double y = Convert.ToInt32(Math.Abs(sty) / yp) * yp;
                Point processedPoint = new Point();
                //processedPoint.Longitude = x;
                //processedPoint.Latitude = y;
                processedPoint.Longitude = Math.Round(x, 8);
                processedPoint.Latitude = Math.Round(y, 8);
                processedPoints.Add(processedPoint);
            }
            return processedPoints;
        }

        public static IList<Point> CleanPolygons(IList<Point> iPolyPts)
        {
            var uniquePolyPointList = iPolyPts.Distinct(new DistinctPointComparer());
            return uniquePolyPointList.ToList();
        }


        public class DistinctPointComparer : IEqualityComparer<Point>
        {

            public bool Equals(Point firstPt, Point secondPt)
            {
                return firstPt.Longitude == secondPt.Longitude &&
                    firstPt.Latitude == secondPt.Latitude;
            }

            public int GetHashCode(Point obj)
            {
                return obj.Longitude.GetHashCode() ^
                    obj.Latitude.GetHashCode();
            }
        }
    }
}